package xyz.thoughtset.viewer.modules.ds.core.service;

import org.springframework.beans.factory.annotation.Autowired;
import xyz.thoughtset.viewer.common.crud.core.service.BaseServiceImpl;
import xyz.thoughtset.viewer.modules.ds.core.dao.DsConfigDao;
import xyz.thoughtset.viewer.modules.ds.core.entity.DsConfig;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.thoughtset.viewer.modules.ds.core.factory.ConnectFactory;

import javax.sql.DataSource;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Transactional
public class DsConfigServiceImpl extends BaseServiceImpl<DsConfigDao, DsConfig> implements DsConfigService {
    @Autowired
    private ConnectFactory connectFactory;

    @SneakyThrows
    @Override
    public Object saveData(LinkedHashMap<String, Object> baseMap) {
        String settingsKey = "otherSettings";
        Object settings = baseMap.remove(settingsKey);
        DsConfig o = convertValue(baseMap);
        if (Objects.nonNull(settings)){
            o.setOtherSettings(mapper.writeValueAsString(settings));
        }
        saveOrUpdate(o);
        return o;
    }

//    @Override
//    public DsConfig selectDetail(String pkey) {
//        DsConfig config = baseMapper.selectById(pkey);
////        config.setSk(StringUtils.hasText(config.getSk()) ?null:"******");
//        return config;
//    }

    @Override
    public DataSource buildDataSource(String dsId) {
        return (DataSource) connectFactory.buildConnect(dsId);
//        DataSource result = DS_CACHE.get(dsId);
//        if (result!=null) return result;
//        DsConfig dsc = baseMapper.selectDetail(dsId);
//        HikariConfig config = new HikariConfig();
//        String settingsStr = dsc.getOtherSettings();
//        if(StringUtils.hasText(settingsStr)){
//            LinkedHashMap<String,String> settings = null;
//            try {
//                settings = mapper.readValue(settingsStr, LinkedHashMap.class);
//            } catch (JsonProcessingException e) {
//                throw new RuntimeException(e);
//            }
//            if (settings!=null){
//                Properties properties = new Properties();
//                properties.putAll(settings);
//                config = new HikariConfig(properties);
//            }
//        }
//        config.setConnectionTestQuery(dsc.getTestQuery());
//        config.setJdbcUrl(dsc.getUrl());
//        config.setUsername(dsc.getAk());
//        config.setPassword(dsc.getSk());
//        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
//        result = new HikariDataSource(config);
//        DS_CACHE.put(dsId,result);
//        return result;
    }
}
